package com.ruoyi.web.controller.cat;

import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.ruoyi.cat.domain.AlipayConfig;
import com.ruoyi.cat.domain.CatBasedataTable;
import com.ruoyi.cat.domain.CatTradedetailTable;
import com.ruoyi.cat.domain.VO.OrderQueryVO;
import com.ruoyi.cat.domain.VO.SysOracleVO;
import com.ruoyi.cat.service.ICatBasedataTableService;
import com.ruoyi.cat.service.ICatTradedetailTableService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.OrderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Api(tags = "管理端-支付宝支付相关")
@RestController
@RequestMapping("/system/alipayOracle")
public class AlipayController extends BaseController {

    @Value("${unionpay.pay-callback-host}")
    private String payCallbackHost;

    @Value("${unionpay.notify}")
    private String notify;

    @Value("${unionpay.returnCallback}")
    private String returnCallback;

    private static final String TRADE_SUCCESS = "TRADE_SUCCESS";
    private static final String TRADE_FINISHED = "TRADE_FINISHED";
    private static final String PAYMENT_TYPE_ALIPAY = "2";
    private static final String INITIAL_STATUS = "0";
    private static final String SUCCESS_STATUS = "1";

    @Autowired
    private ICatBasedataTableService catBasedataTableService;

    @Autowired
    private ICatTradedetailTableService catTradedetailTableService;

    @PostMapping("/pagePay")
    @ApiOperation(value = "PC端-支付宝支付")
    public AjaxResult pagePay(@RequestBody SysOracleVO sysOracleVO, HttpServletResponse response) {
        try {
            AlipayConfig alipayConfig = getAlipayConfig();
            AlipayClient alipayClient = createAlipayClient(alipayConfig);
            String orderNo = OrderUtil.makeOrderNo();
            log.info("这个值是什么呢 {} ",sysOracleVO);
            BigDecimal totalAmount = calculateTotalAmount(sysOracleVO);

            // Create and save trade record first
            CatTradedetailTable tradeRecord = createTradeRecord(orderNo, totalAmount,sysOracleVO.getUserId(),sysOracleVO.getId());
            catTradedetailTableService.insertCatTradedetailTable(tradeRecord);

            // Generate payment form
            String form = generatePaymentForm(alipayClient, orderNo, totalAmount);
            Map<String, String> result = new HashMap<>();
            result.put("form",form);
            result.put("orderNo",orderNo);
            return success(result);

        } catch (Exception e) {
            log.error("支付发起失败", e);
            return error("支付发起失败: " + e.getMessage());
        }
    }

  /*  @PostMapping("/pagePay")
    @ApiOperation(value = "PC端-支付宝扫码支付")
    public AjaxResult wapPay(@RequestBody SysOracleVO sysOracleVO) {
        try {
            AlipayConfig alipayConfig = getAlipayConfig();
            AlipayClient alipayClient = createAlipayClient(alipayConfig);
            String orderNo = OrderUtil.makeOrderNo();
            BigDecimal totalAmount = calculateTotalAmount(sysOracleVO);

            // 创建交易记录
            CatTradedetailTable tradeRecord = createTradeRecord(orderNo, totalAmount);
            catTradedetailTableService.insertCatTradedetailTable(tradeRecord);

            // 创建请求
            AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
            // request.setReturnUrl(payCallbackHost + "/system/alipayOracle/return");
            request.setNotifyUrl(payCallbackHost + notify);

            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", orderNo);
            bizContent.put("total_amount", totalAmount.toString());
            bizContent.put("subject", "文章购买");
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            // 设置qr_pay_mode，支持前置模式
            bizContent.put("qr_pay_mode", "4");
            bizContent.put("qr_code_width", 200);

            request.setBizContent(new JSONObject(bizContent).toString());

            // 调用支付宝接口获取支付表单
            String form = alipayClient.pageExecute(request).getBody();



            // 构建返回结果
            Map<String, String> result = new HashMap<>();
            result.put("form", form);
            result.put("orderNo", orderNo);

            return success(result);

        } catch (Exception e) {
            log.error("支付发起失败", e);
            return error("支付发起失败: " + e.getMessage());
        }
    }*/

    @GetMapping("/returnCallback")
    public void returnCallback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Map<String, String> params = convertRequestToMap(request);
            log.info("支付宝同步回调，params：{}", params);

            if (verifyAlipaySign(params)) {
                String orderNo = params.get("out_trade_no");
                handleSuccessfulPayment(orderNo, params);
                CatTradedetailTable catTradedetailTable = catTradedetailTableService.selectCatTradedetailTableByOrderNo(orderNo);
                log.error("----------好的--------回调");
                response.sendRedirect("https://web.jiubeimao.com/article/editArticleTask?orderNo=" + orderNo+"&id="+catTradedetailTable.getActivityId());
            } else {
                log.error("支付宝同步回调签名认证失败");
                response.sendRedirect("http://你的域名/payment/fail");
            }
        } catch (Exception e) {
            log.error("支付宝同步回调处理异常", e);
            response.sendRedirect("http://你的域名/payment/fail");
        }
    }

    @PostMapping("/notify")
    public String notifyCallback(HttpServletRequest request) {
        try {
            Map<String, String> params = convertRequestToMap(request);
            log.info("支付宝异步回调，params：{}", params);

            if (verifyAlipaySign(params)) {
                String orderNo = params.get("out_trade_no");
                String tradeStatus = params.get("trade_status");

                if (isSuccessfulTradeStatus(tradeStatus)) {
                    updateOrderStatus(orderNo, params.get("trade_no"));
                    return "success";
                }
            }
        } catch (Exception e) {
            log.error("支付宝异步回调处理异常", e);
        }
        return "fail";
    }

    @GetMapping("/query/{orderNo}")
    @ApiOperation("查询支付状态")
    public AjaxResult queryPaymentStatus(@PathVariable String orderNo) {
        try {
            AlipayConfig config = getAlipayConfig();
            AlipayClient alipayClient = createAlipayClient(config);

            System.out.println("---------查询支付状态--------"+orderNo);
            AlipayTradeQueryResponse response = queryAlipayTrade(alipayClient, orderNo);

            if (response.isSuccess()) {
                Map<String, String> result = createQueryResult(response);
                if (isSuccessfulTradeStatus(response.getTradeStatus())) {
                    updateOrderStatus(orderNo, response.getTradeNo());
                }
                return success(result);
            }
            return error("查询失败：" + response.getMsg());
        } catch (AlipayApiException e) {
            log.error("查询支付状态异常", e);
            return error("查询异常");
        }
    }

    // Private helper methods
    private AlipayClient createAlipayClient(AlipayConfig config) {
        return new DefaultAlipayClient(
                config.getServerUrl(),
                config.getAppId(),
                config.getPrivateKey(),
                config.getFormat(),
                config.getCharset(),
                config.getAlipayPublicKey(),
                config.getSignType()
        );
    }

    private BigDecimal calculateTotalAmount(SysOracleVO sysOracleVO) {
        CatBasedataTable catBasedataTable = catBasedataTableService.selectCatBasedataTableById(1L);
        return OrderUtil.calculateProduct(sysOracleVO.getTargetNum(), catBasedataTable.getBaseCost());
    }

    private String generatePaymentForm(AlipayClient alipayClient, String orderNo, BigDecimal totalAmount) throws AlipayApiException {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
       // request.setReturnUrl(payCallbackHost+returnCallback);
        System.out.println("------------"+totalAmount.toString());
        request.setNotifyUrl(payCallbackHost+notify);
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount(OrderUtil.formatForAlipay(totalAmount));
        model.setSubject("文章购买");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setQrPayMode("1");
        model.setQrcodeWidth(100L);
        request.setBizModel(model);

        return alipayClient.pageExecute(request).getBody();
    }

    private CatTradedetailTable createTradeRecord(String orderNo, BigDecimal amount,Long userId,Long id) {
        CatTradedetailTable record = new CatTradedetailTable();
        record.setOrderNo(orderNo);
        record.setTradeNum(amount);
        record.setTradeTitle("文章购买");
        record.setTradeType("1");
        record.setPaymentType(PAYMENT_TYPE_ALIPAY);
        record.setStatus(INITIAL_STATUS);
        record.setUserId(userId);
        record.setActivityId(id);
        record.setType("1");
        return record;
    }

    private boolean verifyAlipaySign(Map<String, String> params) throws AlipayApiException {
        AlipayConfig config = getAlipayConfig();
        return AlipaySignature.rsaCheckV1(
                params,
                config.getAlipayPublicKey(),
                config.getCharset(),
                config.getSignType()
        );
    }

    private void updateOrderStatus(String orderNo, String tradeNo) {
        CatTradedetailTable updateOrder = new CatTradedetailTable();
        updateOrder.setOrderNo(orderNo);
        updateOrder.setStatus(SUCCESS_STATUS);
        updateOrder.setTradeNo(tradeNo);
        catTradedetailTableService.updateCatTradedetailTableOrderNo(updateOrder);
    }

    private boolean isSuccessfulTradeStatus(String tradeStatus) {
        return TRADE_SUCCESS.equals(tradeStatus) || TRADE_FINISHED.equals(tradeStatus);
    }

    private void handleSuccessfulPayment(String orderNo, Map<String, String> params) {
        log.info("支付成功 - 订单号: {}, 支付宝交易号: {}, 支付金额: {}",
                orderNo,
                params.get("trade_no"),
                params.get("total_amount"));
    }

    private AlipayTradeQueryResponse queryAlipayTrade(AlipayClient alipayClient, String orderNo) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, String> bizContent = new HashMap<>();
        bizContent.put("out_trade_no", orderNo);
        request.setBizContent(new JSONObject(bizContent).toString());
        return alipayClient.execute(request);
    }

    private Map<String, String> createQueryResult(AlipayTradeQueryResponse response) {
        Map<String, String> result = new HashMap<>();
        result.put("tradeStatus", response.getTradeStatus());
        result.put("totalAmount", response.getTotalAmount());
        result.put("tradeNo", response.getTradeNo());
        return result;
    }

    private Map<String, String> convertRequestToMap(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        return params;
    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2GKCLfowv5cDbfH3GHRkqvnfZcfr/rn561uPz5Ys5ottObtt5pOt1ywKvoLLECgYEA0wnhuTpqyI6MWcAjKSd0mwDxj+52vr7auk+sLIzSphHgbnbR2/yX9BWWMNymGkUxT3exbjCrlqHwbefDT05nuJBzoJ1d03nG0zwrZ0N45FSiDVZS0jQ+d2PQhMtLl6SR5cJLtRT3rp4GSudEEofwGoPWnJq/0jtJaVrj43D1nqcCgYBIFnGARTKndpEU76grxURqs4ZrfMzVrengb13/mFNm9qzj6b14iTtmuuGkF+Ix1FIQM7VGLth8Mt1PANoh0huUzrmSBAtEaaPeoUOotjJbAYhsubANknC6d619FKMl8xSU5ha3942Iw05QqVD24nt4joQGzaZCEDhjkqwgKqGWkQKBgQCvxE3YXmBspe8ZqUBZQoo+hskrBqo7RCJCBUwbWVMzhuPy8fIyz7KdO/M9EYEDdYQs7g7LDquxVar4bfOZUGNpFFqnNJ21cbWnOKS+lSOSQdGvQzevvxRUxZ9rA+mUd+zLAKmA+xi+7ZajYnTWCEP1KS3/0lFGzQjvg6ZE62iC5g==";
        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAidvBOZzQoZ2KEKFUdXOGPwj5tPD72ZqlZl7JPLjDUES4rAZgAvP3YsNHLq5tWkV5W9tSYOVnsT6Ru1QOhJ7Bn9TWLlcV6f7knVQz4UJxvOFpK7Ps7QHvz9m0PYtse/b3ll/8eYhJHe6rRP3JKilqYsWTw4X8gAj8dr9xiLEsgqm1cKkM+cJH+m2qLEkBi3A6v5o5LoedjtwqoA4vhS4v6r+2f6V3LHyYpGeR7zHzaxs8aR57uBiuHes8acHTT9utpb90EtA/AmT+azGD4LOkjXI9warNv6CRANtj0bOf/+xSGFl3g1OG08GECLSFj2HNiFd1WVoYNQdUZlOG/mOBoQIDAQAB";
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId("2021005116671077");
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setFormat("json");
        alipayConfig.setAlipayPublicKey(alipayPublicKey);
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");
        return alipayConfig;
    }


/**
 * 应用私钥
 * MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCr9jWVG/V6Nz1nmAdus9S9x5qk8cnAoSa4dPRcKao7j/HxK0ukN7kCF9TB5HmjSaNQiAhezaAQGFNd0cBWgHPgL66jXAA2fOmdhUHsu95Qe8cFuletr/Ely7JREloX0b2gm9wHaro1f69rGyOGfgrTN6V6Dppqp8jtNxxVXg8cxVA+7XYiiz5gpV+D8XEnd/Cgnsdy3nURqDtRficc57CegFihpj5Ceva546m7Ws1F5U/pYMZ4NphGSHBQjquoDRRN+6XFCsFpmOJBsKZJWrKuDjbKIDcuTGsVphtJqFrpAHuUNU4WhdqGUWeOvR2vqtM7DKvOOalyvoMNirFAPf61AgMBAAECggEAZystFIuUqEFyBq/wbZtYnI+fmSwzBe3pRCtu28hniJqg5jc6h4ii572SeM1xqOSqJcuncfFeAaoGgjgwc/VXD/6rgPjWa9pfcpEbb0N7asAINMiKh/sR68Ic9oTTJo1AfpZj2NNQan5zqQe8NZlzNyugjO0r+ac2ZhN1XUY0POasqB56Df5kLZVchmN+qWxkM1dpFywtrPeNBtuoDCeyVErMilkEPY7yniDQ1bZR3qmocKkY6IPEczOi+bsC8R6IzeD+7W8LDWv/bvWYvaRHJwARt8mNwsmDIcOlFZxPNCUzrLk4NdJ5OJSn+VcDiDPj8IE1NYM4rhDcdeTxTy2P1QKBgQDUxtv0b0pIap6RIdxkUEn78Az8BtzdxQn6g8AD2InKEaRD3Mf/OtoIEbHv05UlLycAnDFUW4CrPromYefJZH+b7ehuApzqUx/JsFq2KLSVCa6QOhp8a99Rk/q+9TEhMPaJBqaaW4Z0DDP5xtCqbcFrPe3Z12T/k5SmZnf/4r1jowKBgQDO5NMgBXucADZpr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